package com.ztom.top100;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的层序遍历
 * <p>
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 *
 * @author ZhangTao
 */
public class Code41LevelOrder {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Deque<TreeNode> queue = new LinkedList<>();
        queue.addFirst(root);
        TreeNode node = null;
        while (!queue.isEmpty()) {
            // 当前层的节点数
            int curLevelSize = queue.size();
            // 收集当前层节点
            List<Integer> nodes = new ArrayList<>();
            while (curLevelSize-- > 0) {
                node = queue.pollLast();
                if (node != null) {
                    nodes.add(node.val);
                    if (node.left != null) {
                        queue.addFirst(node.left);
                    }
                    if (node.right != null) {
                        queue.addFirst(node.right);
                    }
                }
            }
            res.add(nodes);
        }

        return res;
    }

    public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        // 当前层尾结点
        TreeNode curEnd = root;
        // 下一层尾结点
        TreeNode nextEnd = null;

        Deque<TreeNode> queue = new LinkedList<>();
        queue.addFirst(root);

        TreeNode node = null;
        List<Integer> nodes = new ArrayList<>();
        while (!queue.isEmpty()) {
            node = queue.pollLast();
            if (node != null) {
                nodes.add(node.val);
                if (node.left != null) {
                    queue.addFirst(node.left);
                    nextEnd = node.left;
                }
                if (node.right != null) {
                    queue.addFirst(node.right);
                    nextEnd = node.right;
                }
            }
            if (node == curEnd) {
                // 准备下一层
                curEnd = nextEnd;
                res.add(nodes);
                nodes = new ArrayList<>();
            }
        }
        return res;
    }
}
